/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.common.query;

import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.Serial;
import java.io.Serializable;
import java.util.List;

/**
 * 查询参数基类
 *
 * @author 挺好的 2023年05月30日 15:32
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode (callSuper = false)
@SuperBuilder
public abstract class BaseQueryable implements Serializable {

    @Serial
    private static final long serialVersionUID = 6324136714507270372L;

    /**
     * 搜索条件
     */
    private List <Filter> filters;

    /**
     * 排序条件
     */
    private List <Order> orders;

    /**
     * group by 条件
     */
    private List <String> groups;

    /**
     * 是否启用默认排序。 默认为true，表示，继承自BaseEntity-> id DESC /OrderEntity-> order ASC 的实体都会进行排序
     */
    private Boolean isEnableDefaultOrder = true;

    /**
     * 根据key
     *
     * @param key
     *         属性的key
     *
     * @return 当前key对应的值
     */
    public Object getValue (String key) {
        if (StringUtils.isEmpty(key) || CollectionUtils.isEmpty(this.filters)) {
            return null;
        }

        Filter filter = this.filters.stream().filter(filter1 -> StringUtils.equals(filter1.getProperty(), key))
                .findAny().orElse(null);

        if (filter == null) {
            return null;
        }

        return filter.getValue();
    }

    /**
     * 移除指定的key
     *
     * @param key
     *         指定的搜索条件
     */
    public void remove (String key) {

        if (StringUtils.isEmpty(key)) {
            return;
        }

        Filter filter = this.filters.stream().filter(filter1 -> StringUtils.equals(filter1.getProperty(), key))
                .findAny().orElse(null);

        if (filter == null) {
            return;
        }

        this.filters.remove(filter);
    }
}
